package third;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Jsoup解析类 <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-11 11:15
 * @since 1.0.0
 */
public final class JsoupTools {

    private JsoupTools() {
    }

    public static String resolveTitle(String html) {
        Document document = Jsoup.parse(html);
        return document.getElementsByTag("title").get(0).text();
    }

    public static Map<String, String> parse(String html, String cssQuery, String attr) {
        if (html == null || html.trim().equals("")) {
            return null;
        }
        Document document = Jsoup.parse(html);
        Elements elements = document.select(cssQuery);
        Map<String, String> map = new LinkedHashMap<>();
        for (Element element : elements) {
            String text = element.text();
            String attrVal = element.attr(attr);
            if (text == null || text.trim().equals("")) {
                text = attrVal;
            }
            map.put(text, attrVal);
        }
        return map;
    }

    public static Map<String, String> parseATag(String html) {
        if (html == null || html.trim().equals("")) {
            return null;
        }
        Document document = Jsoup.parse(html);
        Elements elements = document.select("a[href]");
        int count = 0;
        Map<String, String> map = new HashMap<>();
        for (int i = 0, size = elements.size(); i < size; i++) {
            Element element = elements.get(i);
            String href = element.attr("href");
            String text = element.text();
            System.out.println(text + ":" + href);
            map.put(text, href);
            count++;
        }
        System.out.println("解析a标签:" + count + "条");
        return map;
    }
}
